<?php
include_once("common/init.php");
check_loginuser();
$info = db_get_row("select * from user where id=".$_SESSION["id"]);
// 设置中国时区
date_default_timezone_set('PRC');
$dingdanhao=date("YmjHis").$info['id'];
$addressid=$_POST['addressid'];
$address = db_get_row("select * from address where id=".$addressid);
$tel=$address['tel'];
$shouhuoren=$address['nickname'];
$sex=$address['sex'];
$addresstitle = $address['title'];
$xiadanren=$_SESSION['account'];
$zt="已付款";
$total = 0;
$cart_id = $_POST['cart_id'];
for($i=0;$i<count($cart_id);$i++){
	$cart=db_get_row("select * from cart where id=".$cart_id[$i]."");
	$gooda=db_get_row("select * from goods where id=".$cart["goodsid"]."");
	if($gooda['amount']<$cart["sums"]){urlMsg($gooda['title']."购买大于库存","cart.php");die;};
	$total = $total+$gooda['sprice']*$cart['sums'];
}
$data = array();
$data["onumber"] = "'". $dingdanhao ."'";
$data["tel"] = "'". $address["tel"] ."'";
$data["address"] = "'". $address["title"] ."'";
$data["shfs"] = "'". $_POST["shfs"] ."'";
$data["zffs"] = "'". $_POST["zffs"] ."'";
$data["nickname"] = "'". $address["nickname"] ."'";
$data["userid"] = "'". $_SESSION['id'] ."'";
$data["content"] = "'". $_POST["content"] ."'";
$data["account"] = "'". $xiadanren ."'";
$data["zt"] = "'". $zt ."'";
$data["total"] = "'". $total ."'";
db_add("orders", $data);
$info2=db_get_row("select * from orders where userid=".$info['id']." order by id desc");
for($i=0;$i<count($cart_id);$i++){
	if($cart_id[$i]!=""){
	$cart1=db_get_row("select * from cart where id=".$cart_id[$i]."");
	$info1=db_get_row("select * from goods where id=".$cart1["goodsid"]."");
	$data = array();
	$data["goodsid"] = "'".$info1["id"]."'";
	$data["nums"] = "'".$cart1["sums"]."'";
	$data["price"] = "'".$info1["sprice"]."'";
	$data["userid"] = "'".$info["id"]."'";
	$data["ordersid"] = "'".$info2["id"]."'";
	$data["onumber"] = "'".$info2["onumber"]."'";
	$data["categoryid"] = "'".$info1["categoryid"]."'";
	$data["addtime"] = "'".date("Y-m-d")."'";
	$data["usersid"] = "'".$info1["userid"]."'";
	$data["totals"] = "'".$info1["sprice"]*$cart1["sums"]."'";
	$data["title"] = "'".$info1["title"]."'";
	$data["zt"] = "'". $zt ."'";
	db_add("ordersta",$data);
	}
}
$ordersid= $info2["id"];
$ordersta = db_get_all("select * from ordersta where ordersid=".$ordersid." order by id desc");

// 付款后商品数量减一
foreach($ordersta as $ordersrow1) {
	db_query("update goods set amount=amount-".$ordersrow1['nums']." where id=".$ordersrow1["goodsid"]."");
}
db_query("update orders set zt='已付款' where id=".$ordersid);
db_query("update ordersta set zt='已付款' where ordersid=".$ordersid);
urlMsg("付款成功", "user/index.php");
die;
?>